package com.runa.rccprotocol.analysis.En13757.decoder;

import com.runa.rccprotocol.analysis.En13757.HeadInfo;
import com.runa.rccprotocol.analysis.En13757.Tail;
import com.runa.rccprotocol.analysis.En13757.UnitData;

import java.util.ArrayList;
import java.util.List;

/**
 * @author diandian
 * @Date 2021/11/9 8:49
 * 标准欧标报文解析
 */
public abstract class AbsEnDecoder extends DecoderSet {

    private int unitDataNumber = 0;

    public abstract int check();

    protected abstract HeadInfo getHeadInfo();

    protected Tail getTail() {
        return null;
    }

    public abstract void decodeUnitValue(UnitData unitValue);

    //    protected List<UnitData> getUnitData(HeadInfo headInfo) {
    public List<UnitData> getUnitData(int dataLength, int headEndIndex) {
        List<UnitData> result = new ArrayList<>(20);
        //如果有数据，且当前下标没有超过数据域，说明还有数据需要解析
        while (this.hasNext() && headEndIndex + dataLength > this.getCurrentIndex()) {
            //标准的欧标数据解析
            UnitData unitValue = this.getNextUnitValue();

            //自定义的数据解析
            decodeUnitValue(unitValue);

            result.add(unitValue);
        }
        return result;
    }

    private UnitData getNextUnitValue() {
        DIF dif = new DIF(this);
        VIF vif = new VIF(this);


        Object value = handleData(dif,vif);
        if (value instanceof Number) {
            value = vif.handle((Integer) value);
        }

        UnitData unitData = new UnitData(dif, vif, ++unitDataNumber, value);

        return unitData;
    }


    private Object handleData(DIF dif, VIF vif) {
        dif.setDif_function(vif);
        return dif.handleData();
    }
}